package com.cms.common.model.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.persistence.Entity;
import javax.persistence.Transient;
import javax.servlet.http.HttpServletRequest;

/**
 * 文件
 * Created by Administrator on 2018/4/2.
 */
@Data
@Entity
public class UploadFile extends BaseEntity {

    private String name;

    private String ext;

    private String type = "img";

    @JsonIgnore
    private String path;

    private String md5;

    @JsonIgnore
    private int pointCount = 0;//引用,等于1时删除才能真正删除

    @JsonIgnore
    private String thumbnail;//缩略图

    @JsonIgnore
    private Long size;


    @Transient
    private String url;

    @Transient
    private String thumb;

    public String getUrl() {
        return fileUrl() + "/api/file/" + md5;
    }

    public String getThumb() {
        return fileUrl() + "/api/file/" + md5 + "/thumb/80/80";
    }

    private String fileUrl() {
        String tUrl = "";
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            tUrl = request.getRequestURL().toString();
            tUrl = tUrl.replace("http://", "http:####");
            tUrl = tUrl.replace("https://", "https:####");
            tUrl = tUrl.trim();
            int index = tUrl.indexOf("/");
            if (index > -1) {
                tUrl = tUrl.substring(0, index);
            }
            tUrl = tUrl.replace("http:####", "http://");
            tUrl = tUrl.replace("https:####", "https://");
        }
        return tUrl;
    }
}
